package com.zhuang.taiqiu.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhuang.taiqiu.config.GCmd;
import com.zhuang.taiqiu.config.SessionManage;
import com.zhuang.taiqiu.model.*;
import com.zhuang.taiqiu.model.vo.RoomInfoVO;
import com.zhuang.taiqiu.proto.GameMessageOuterClass.GameMessage;
import com.zhuang.taiqiu.utils.NettyUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class HitBallHandler {


    /**
     * 处理击球事件
     * @param ctx
     * @param msg
     */
    public void handleHitBallEvent(ChannelHandlerContext ctx, GameMessage msg) {
        processLogic(ctx, msg, false);
    }

    /**
     * 处理击球完成事件
     * @param ctx
     * @param msg
     */
    public void handleHitBallCompleteEvent(ChannelHandlerContext ctx, GameMessage msg) {
        processLogic(ctx, msg, true);
    }


    private static void processLogic(ChannelHandlerContext ctx, GameMessage msg, boolean isComplete) {
        JSONObject jsonParse = JSON.parseObject(msg.getData());
        Long userId = jsonParse.getLong("userId");
        Long roomId = jsonParse.getLong("roomId");
        Coordinate ballPos = jsonParse.getObject("ballPos", Coordinate.class);//白球位置
        Coordinate ballQuat = jsonParse.getObject("ballQuat", Coordinate.class);//白球旋转角度
        Coordinate hitImpulse = jsonParse.getObject("hitImpulse", Coordinate.class);//击球力度
//        JSONArray beHitBallsPos = jsonParse.getJSONArray("beHitBallsPos");//其他球位置
//        JSONArray beHitBallsQuat = jsonParse.getJSONArray("beHitBallsQuat");//其他球角度
        JSONArray beBallsJSONArray = jsonParse.getJSONArray("beBalls");//其他球角度
        JSONArray goalScoredsJSONArray = jsonParse.getJSONArray("goalScoreds");//进球的数组

//        Double[] beHitBallsPosArray = beHitBallsPos.toJavaList(Double.class).toArray(new Double[0]);
//        Double[] beHitBallsQuatArray = beHitBallsQuat.toJavaList(Double.class).toArray(new Double[0]);
        List<QiuData> beBalls = beBallsJSONArray.toJavaList(QiuData.class);

        /**直接转发给房内所有玩家
         * 前端的逻辑应该是先把发球指令发到服务器，无需等待服务器回复，自己执行渲染*/
        FrameInfo frameInfo = new FrameInfo();
        RoomInfo channelRoomInfo = SessionManage.getChannelRoomInfo(roomId);
        if(null == channelRoomInfo){
            NettyUtil.sendMsg(ctx.channel(), frameInfo, GCmd.S2C.HIT_BALL_SYNC.getDescription());
            return;
        }
        channelRoomInfo.setCurrentPlayer(userId);

        frameInfo.setUserId(userId);
        frameInfo.setBallPos(ballPos);
        frameInfo.setBallQuat(ballQuat);
        frameInfo.setHitImpulse(hitImpulse);
//        frameInfo.setBeHitBallsPos(beHitBallsPosArray);
//        frameInfo.setBeHitBallsQuat(beHitBallsQuatArray);
        frameInfo.setBeBalls(beBalls);
        frameInfo.setFreeKick(false);

        ChannelGroup channelGroup = channelRoomInfo.getChannelGroup();

        if(isComplete){
            Player playerA = channelRoomInfo.getPlayerA();
            Player playerB = channelRoomInfo.getPlayerB();

            boolean isSync = false;
            //如果有进球，就进按进去逻辑，如果没进球，就按轮流打球的逻辑
            if(null != goalScoredsJSONArray && goalScoredsJSONArray.size() > 0){
                List<String> goalScoreds = goalScoredsJSONArray.toJavaList(String.class);
                if(null != goalScoreds && goalScoreds.size() > 0){
                    for (String goalScored : goalScoreds) {
                        //获取到这个后，判断是不是白球，如果不是就加一分，是把球的要求可以让对发任意球
                        if("ball-0".equalsIgnoreCase(goalScored)){
                            //让对手任意球
                            frameInfo.setFreeKick(true);
//                            frameInfo.setBallPos(null);
//                            frameInfo.setBallQuat(null);
                            //轮流打球的逻辑
                            if(playerA.getUser().getId().equals(userId) ){
                                frameInfo.setCurrentPlayer(playerB.getUser().getId());
                                Integer score = playerA.getUser().getScore();
                                playerA.getUser().setScore(score - 2);
                            }else{
                                frameInfo.setCurrentPlayer(playerA.getUser().getId());
                                Integer score = playerB.getUser().getScore();
                                playerB.getUser().setScore(score - 2);
                            }
                        }else {
                            //如果进球了自己继续打球，自己得一分
                            if(playerA.getUser().getId().equals(userId) ){
                                frameInfo.setCurrentPlayer(playerA.getUser().getId());
                                Integer score = playerA.getUser().getScore();
                                playerA.getUser().setScore(score + 1);
                            }else{
                                frameInfo.setCurrentPlayer(playerB.getUser().getId());
                                Integer score = playerB.getUser().getScore();
                                playerB.getUser().setScore(score + 1);
                            }
                        }
                    }
                    RoomInfoVO roomInfoVO = new RoomInfoVO();
                    roomInfoVO.setPlayerA(playerA.getUser());
                    roomInfoVO.setPlayerB(playerB.getUser());
                    frameInfo.setRoomInfo(roomInfoVO);
                    isSync = true;
                }
            }

            if(!isSync){
                //轮流打球的逻辑
                if(playerA.getUser().getId().equals(userId) ){
                    frameInfo.setCurrentPlayer(playerB.getUser().getId());
                }else{
                    frameInfo.setCurrentPlayer(playerA.getUser().getId());
                }
            }


            NettyUtil.sendGroupMsg(channelGroup, frameInfo, GCmd.S2C.HIT_BALL_COMPLETE_SYNC.getDescription());
            return;
        }
        NettyUtil.sendGroupMsg(channelGroup, frameInfo, GCmd.S2C.HIT_BALL_SYNC.getDescription());

    }
}
